<template>
  <el-drawer
    v-model="drawerVisible"
    title="用户下单记录"
    size="800px"
    direction="rtl"
    @close="handleClose"
  >
    <!-- 顶部汇总 & 工具条 -->
    <div class="toolbar">
      <div class="stats">
        <el-tag type="info" effect="plain">共 {{ orderCount.count }} 笔</el-tag>
        <el-tag type="success" effect="plain" class="ml-8">
          累计金额：{{ formatCurrency(orderCount.totalAmount) }}
        </el-tag>
      </div>
      <div class="actions">
        <el-input
          v-model="keyword"
          placeholder="搜 订单号/名称/收货人/来源/业务员"
          clearable
          :prefix-icon="Search"
          class="w-100"
        />
        <el-switch v-model="desc" active-text="新 → 旧" inactive-text="旧 → 新" class="ml-8" />
      </div>
    </div>

    <!-- 空态 -->
    <div v-if="!orderCount.count && !loading" class="empty-box">
      <el-icon><document-remove /></el-icon>
      <div>暂无订单记录</div>
    </div>

    <!-- 时间线 + Descriptions 展示 -->
    <div v-else class="scroll-area" @scroll.passive="handleScroll" ref="scrollContainer">
      <el-timeline :reverse="false" class="mt-12">
        <el-timeline-item
          v-for="order in filteredOrderData"
          :key="order.orderId"
          :timestamp="formatDate(order.orderDate)"
          :type="order.signDate ? 'success' : 'warning'"
        >
          <el-card shadow="never" class="order-card">
            <!-- 订单信息 -->
            <el-descriptions :column="2" border size="small" :title="`订单 #${order.orderId}`">
              <template #extra>
                <el-space wrap>
                  <el-tag :color="orderStatusStr(order.orderStatus).color">
                    <span style="color: #fff">
                      {{ orderStatusStr(order.orderStatus).text }}
                    </span>
                  </el-tag>
                  <el-button text size="small" @click="copy(order.orderId)">
                    <el-icon class="mr-4"><copy-document /></el-icon>复制单号
                  </el-button>
                </el-space>
              </template>

              <el-descriptions-item label="商品名称">{{ order.productSpec }}</el-descriptions-item>
              <el-descriptions-item label="商品数量">{{ order.nums }}</el-descriptions-item>

              <el-descriptions-item label="订单金额">
                {{ formatCurrency(order.orderPrice) }}
              </el-descriptions-item>
              <el-descriptions-item label="实付金额">
                {{ formatCurrency(order.actualPrice) }}
              </el-descriptions-item>

              <el-descriptions-item label="下单日期">
                {{ formatDate(order.orderTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="签收日期">
                {{ order.signDate ? formatDate(order.signDate) : '未签收' }}
              </el-descriptions-item>

              <el-descriptions-item label="下发业务员">{{ order.salesman }}</el-descriptions-item>
              <el-descriptions-item label="订单号">
                <el-space>
                  <span>{{ order.orderId }}</span>
                  <el-button text size="small" @click="copy(order.orderId)">
                    <el-icon class="mr-2"><copy-document /></el-icon>复制
                  </el-button>
                </el-space>
              </el-descriptions-item>
            </el-descriptions>

            <!-- 配送信息 -->
            <el-descriptions title="配送信息" :column="2" border size="small" class="mt-12">
              <el-descriptions-item label="收货人">{{ order.receiverName }}</el-descriptions-item>
              <el-descriptions-item label="电话">
                <el-space>
                  <el-link :href="`tel:${order.receiverPhone}`" type="primary">
                    {{ order.receiverPhone }}
                  </el-link>
                  <el-button text size="small" @click="copy(order.receiverPhone)">
                    <el-icon class="mr-2"><copy-document /></el-icon>复制
                  </el-button>
                </el-space>
              </el-descriptions-item>

              <el-descriptions-item label="地址" :span="2">
                <span class="addr">{{ order.receiverAddress }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <!-- 加载状态 & 无更多 -->
      <div class="load-more">
        <el-icon v-if="loading"><i class="el-icon-loading"></i></el-icon>
        <span v-if="loading">加载中...</span>
        <span v-else-if="noMore && filteredOrderData.length">没有更多了</span>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, nextTick, computed } from 'vue';
import { Search, DocumentRemove, CopyDocument } from '@element-plus/icons-vue';
import { getCustomerOrderCount, listOrderCustomer } from '../../api/customers';
import { orderStatusStr } from '../../utils/order';
import { orderBy } from 'lodash';
import { useClipboard } from '../../hooks/useClipboard';

const { copy } = useClipboard();

// 控制抽屉
const drawerVisible = ref(false);

// 原始缓存数据
const orderCacheData = ref([]);

// 搜索和排序
const keyword = ref('');
const desc = ref(true); // true: 新→旧

// 加载状态与分页
const loading = ref(false);
const noMore = ref(false);
const pageNum = ref(1);
const pageSize = ref(10);
const customerIdRef = ref(null);

// 订单统计
const orderCount = reactive({
  totalAmount: 0,
  count: 0
});

// 使用 computed 统一处理排序 & 搜索（更高效）
const filteredOrderData = computed(() => {
  let data = orderCacheData.value;

  if (!data.length) return [];

  // 搜索
  if (keyword.value) {
    const kw = keyword.value.toLowerCase();
    data = data.filter(
      (o) =>
        String(o.orderId).toLowerCase().includes(kw) ||
        String(o.productSpec).toLowerCase().includes(kw) ||
        String(o.receiverName).toLowerCase().includes(kw) ||
        String(o.orderSource).toLowerCase().includes(kw) ||
        String(o.salesman).toLowerCase().includes(kw)
    );
  }

  // 排序
  return orderBy(data, ['createTime'], [desc.value ? 'desc' : 'asc']);
});

// 格式化金额
function formatCurrency(n) {
  const v = Number(n || 0);
  try {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY'
    }).format(v);
  } catch {
    return `¥${v.toFixed(2)}`;
  }
}

// 格式化日期
function formatDate(d) {
  if (!d) return '';
  const dt = new Date(d);
  if (isNaN(dt)) return d;
  return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(
    dt.getDate()
  ).padStart(2, '0')} ${String(dt.getHours()).padStart(2, '0')}:${String(dt.getMinutes()).padStart(
    2,
    '0'
  )}`;
}

// 打开抽屉并加载第一页
function show({ customerId }) {
  customerIdRef.value = customerId;
  drawerVisible.value = true;
  reset();

  nextTick(() => {
    fetchCount(customerId);
    loadMore(); // 加载第一页
  });
}

function reset() {
  orderCacheData.value = [];
  pageNum.value = 1;
  noMore.value = false;
}

// 获取汇总信息
function fetchCount(customerId) {
  getCustomerOrderCount(customerId).then((res) => {
    if (res.code === 200) {
      orderCount.count = res.data.count || 0;
      orderCount.totalAmount = res.data.totalAmount || 0;
    }
  });
}

// 加载更多
async function loadMore() {
  if (loading.value || noMore.value) return;
  loading.value = true;

  try {
    const res = await listOrderCustomer({
      customerId: customerIdRef.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    });

    if (res.code === 200) {
      const rows = res.rows || [];

      if (rows.length < pageSize.value) noMore.value = true;

      // push 到缓存即可，UI 用 computed
      orderCacheData.value.push(...rows);

      pageNum.value++;
    }
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
}

// 滚动到底部自动加载
function handleScroll(e) {
  const target = e.target;
  const offset = target.scrollHeight - target.scrollTop - target.clientHeight;

  if (offset < 40) {
    loadMore();
  }
}

defineExpose({ show });
</script>

<style lang="scss" scoped>
.toolbar {
  display: flex;
  flex-direction: column;
  gap: 8px;
  .stats {
    display: flex;
    align-items: center;
  }
  .actions {
    display: flex;
    align-items: center;
  }
  .w-100 {
    flex: 1;
  }
  .ml-8 {
    margin-left: 8px;
  }
}

.scroll-area {
  max-height: calc(100vh - 160px);
  overflow-y: auto;
  padding-right: 8px;
}

.mt-12 {
  margin-top: 12px;
}
.ml-8 {
  margin-left: 8px;
}
.mr-2 {
  margin-right: 2px;
}
.mr-4 {
  margin-right: 4px;
}

.empty-box {
  padding: 32px 0;
  color: var(--el-text-color-secondary);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.order-card {
  border-radius: 12px;
}

.addr {
  word-break: break-word;
}

.load-more {
  text-align: center;
  color: var(--el-text-color-secondary);
  padding: 16px 0;
}
</style>

<style lang="scss">
.el-timeline {
  padding: 0;
  margin: 0;
}
</style>
